// 环境变量
import 'xl-ts-plugins/env'
// 全局常量
import { HOST, PORT } from './config'
// express
import express from 'express'
import CorsMidware from './midware/cors-midware'
// typeorm 连接 mysql 数据库
import { createConnection } from 'xl-ts-plugins/typeorm'
import { RegisterController, ApiBaseErrorMidware } from 'xl-ts-plugins/router'

// 实体类
import { User } from './entity/User'
import { Author } from './entity/Author'
import { Photo } from './entity/Photo'
import { UserAmount } from './entity/UserAmount'
import { UserAmountRecord } from './entity/UserAmountRecord'
// 控制器
import UserController from './controller/UserController'
import TestController from './controller/TestController'
import RedisTestController from './controller/RedisTestController'
import TokenTestController from './controller/TokenTestController'
import AuthorController from './controller/AuthorController'
import PhotoController from './controller/PhotoController'
import UserAmountController from './controller/UserAmountController'

// 接口文档
import Swagger from 'xl-ts-plugins/swagger'

// 自定义响应格式
import { ResultModelName, ajaxResultFail } from './utils/custom-result'

const app = express()

createConnection([
  User,
  Author,
  Photo,
  UserAmount,
  UserAmountRecord,
]).then(() => {
  // 跨域
  app.all('*', CorsMidware)

  // 注册控制器
  RegisterController(app, TestController)
  RegisterController(app, UserController)
  RegisterController(app, RedisTestController)
  RegisterController(app, TokenTestController)
  RegisterController(app, AuthorController)
  RegisterController(app, PhotoController)
  RegisterController(app, UserAmountController)

  // 接口文档
  new Swagger(app, '/apidoc', {
    title: 'typescript 学习接口文档',
    host: `${HOST}:${PORT}`,
    defaultResponseModel: ResultModelName
  })

  // 错误处理
  ApiBaseErrorMidware.setDefaultLog()
  app.use(ApiBaseErrorMidware.midware(ajaxResultFail))

  app.listen(PORT, () => {
    console.log(`Server running at port: ${PORT}`)
  })
})
